<?php
namespace App\Validate;

use Hyperf\Validation\Contract\ValidatorFactoryInterface;

class UserValidate extends Validate
{
    /**
     * 获取应用到请求的验证规则
     */
    public function rules(): array
    {
        return [
            'username' => 'required|max:255',
            'password' => 'required',
        ];
    }

    /**
     * 定义场景，验证不同场景的数据
     */
    public function scene(): array
    {
        return [
            'add' => [
                'username',
                'password',
            ],
            'update' => [
                'username'
            ],
        ];
    }

    /**
     * 验证
     * @author yongwei
     * @param array $data
     * @param string $scene
     */
    public function check(array $data, string $scene = 'add')
    {
        $rule = $this->getSceneRule($this->rules(), $this->scene(), $scene);
        $validator = make(ValidatorFactoryInterface::class)->make($data, $rule, $this->messages());
        $errorMessage = '';
        if ($validator->fails()){
            $errorMessage = $validator->errors()->first();
        }
        return $errorMessage;
    }
}